package com.example.myapplication2.db;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Locale;
import java.util.List;
import java.util.ArrayList;
import com.example.myapplication2.model.Task;

public class TaskDao {
    private DatabaseHelper dbHelper;

    public TaskDao(Context context) {
        dbHelper = new DatabaseHelper(context);
    }

    // 生成任务编号 (yy+mm+dd+000)
    private String generateTaskNumber(SQLiteDatabase db) {
        SimpleDateFormat sdf = new SimpleDateFormat("yyMMdd", Locale.getDefault());
        String datePrefix = sdf.format(new Date());
        
        String query = "SELECT " + DatabaseHelper.COLUMN_TASK_NUMBER + 
                      " FROM " + DatabaseHelper.TABLE_TASKS + 
                      " WHERE " + DatabaseHelper.COLUMN_TASK_NUMBER + 
                      " LIKE '" + datePrefix + "%' " +
                      "ORDER BY " + DatabaseHelper.COLUMN_TASK_NUMBER + " DESC LIMIT 1";
        
        String number = datePrefix + "001";
        Cursor cursor = null;
        try {
            cursor = db.rawQuery(query, null);
            if (cursor != null && cursor.moveToFirst()) {
                String lastNumber = cursor.getString(0);
                int sequence = Integer.parseInt(lastNumber.substring(6)) + 1;
                number = String.format("%s%03d", datePrefix, sequence);
            }
        } finally {
            if (cursor != null) {
                cursor.close();
            }
        }
        return number;
    }

    // 添加新任务
    public boolean addTask(String title, String description, String reminderDate, 
                           String reminderTime, int priority, long userId) {
        if (!validateTaskData(title, priority, userId)) {
            return false;
        }

        SQLiteDatabase db = dbHelper.getWritableDatabase();
        try {
            ContentValues values = new ContentValues();
            
            // 使用同一个数据库连接生成编号
            values.put(DatabaseHelper.COLUMN_TASK_NUMBER, generateTaskNumber(db));
            values.put(DatabaseHelper.COLUMN_TITLE, title);
            values.put(DatabaseHelper.COLUMN_DESCRIPTION, description);
            
            // 如果没有设置提醒日期，使用当前日期
            if (reminderDate == null || reminderDate.isEmpty()) {
                SimpleDateFormat sdf = new SimpleDateFormat("yyyy年MM月dd日", Locale.getDefault());
                reminderDate = sdf.format(new Date());
            }
            values.put(DatabaseHelper.COLUMN_REMINDER_DATE, reminderDate);
            
            // 提醒时间可以为空
            if (reminderTime != null && !reminderTime.isEmpty()) {
                values.put(DatabaseHelper.COLUMN_REMINDER_TIME, reminderTime);
            }

            values.put(DatabaseHelper.COLUMN_PRIORITY, priority);
            values.put(DatabaseHelper.COLUMN_IS_COMPLETED, -1);
            values.put(DatabaseHelper.COLUMN_USER_ID, userId);

            long result = db.insert(DatabaseHelper.TABLE_TASKS, null, values);
            return result != -1;
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        } finally {
            if (db != null) {
                db.close();
            }
        }
    }

    // 添加数据验证方法
    private boolean validateTaskData(String title, int priority, long userId) {
        if (title == null || title.trim().isEmpty()) {
            return false;
        }
        if (priority < 0 || priority > 3) {
            return false;
        }
        if (userId <= 0) {
            return false;
        }
        return true;
    }

    public List<Task> getTodayTasks(long userId) {
        List<Task> taskList = new ArrayList<>();
        SQLiteDatabase db = dbHelper.getReadableDatabase();
        
        // 获取今天的日期
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy年MM月dd日", Locale.getDefault());
        String today = sdf.format(new Date());
        
        String selection = DatabaseHelper.COLUMN_REMINDER_DATE + " = ? AND " + 
                          DatabaseHelper.COLUMN_USER_ID + " = ?";
        String[] selectionArgs = {today, String.valueOf(userId)};
        
        Cursor cursor = null;
        try {
            cursor = db.query(
                DatabaseHelper.TABLE_TASKS,
                null,  // 获取所有列
                selection,
                selectionArgs,
                null,
                null,
                DatabaseHelper.COLUMN_CREATE_TIME + " DESC"  // 按创建时间降序排序
            );
            
            if (cursor != null && cursor.moveToFirst()) {
                do {
                    Task task = new Task();
                    task.setId(cursor.getLong(cursor.getColumnIndex(DatabaseHelper.COLUMN_ID)));
                    task.setTaskNumber(cursor.getString(cursor.getColumnIndex(DatabaseHelper.COLUMN_TASK_NUMBER)));
                    task.setTitle(cursor.getString(cursor.getColumnIndex(DatabaseHelper.COLUMN_TITLE)));
                    task.setDescription(cursor.getString(cursor.getColumnIndex(DatabaseHelper.COLUMN_DESCRIPTION)));
                    task.setReminderDate(cursor.getString(cursor.getColumnIndex(DatabaseHelper.COLUMN_REMINDER_DATE)));
                    task.setReminderTime(cursor.getString(cursor.getColumnIndex(DatabaseHelper.COLUMN_REMINDER_TIME)));
                    task.setPriority(cursor.getInt(cursor.getColumnIndex(DatabaseHelper.COLUMN_PRIORITY)));
                    task.setCompleted(cursor.getInt(cursor.getColumnIndex(DatabaseHelper.COLUMN_IS_COMPLETED)) == 1);
                    task.setCreateTime(cursor.getString(cursor.getColumnIndex(DatabaseHelper.COLUMN_CREATE_TIME)));
                    taskList.add(task);
                } while (cursor.moveToNext());
            }
        } finally {
            if (cursor != null) {
                cursor.close();
            }
            db.close();
        }
        
        return taskList;
    }

    // 更新任务完成状态
    public boolean updateTaskStatus(long taskId, boolean isCompleted) {
        SQLiteDatabase db = dbHelper.getWritableDatabase();
        try {
            ContentValues values = new ContentValues();
            values.put(DatabaseHelper.COLUMN_IS_COMPLETED, isCompleted ? 1 : 0);
            
            int result = db.update(
                DatabaseHelper.TABLE_TASKS,
                values,
                DatabaseHelper.COLUMN_ID + " = ?",
                new String[]{String.valueOf(taskId)}
            );
            
            return result > 0;
        } finally {
            db.close();
        }
    }
} 